package top.shiyiri.statement;

import top.shiyiri.util.JDBCUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Scanner;

/**
 * @author Aunean
 * @date 2022/1/17 21:56
 * @Description PrepareStatement 替换 Statement，解决SQL注入问题
 */

/*
除了解决Statement的拼串，SQL注入问题之外，PrepareStatement还有哪些好处？
1.PrepareStatement可以操作Blob的数据，Statement做不到
2.PrepareStatement可以实现更高效的批量操作
 */
public class PrepareStatementTest {

    /*
    针对不同的表的通用的查询操作，返回表中的一条记录
     */
    public static <T> T getInstance(Class<T> clazz, String sql, Object ... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);

            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            //执行，获取结果集
            rs = ps.executeQuery();
            //获取结果集的元数据
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();//获取列数
            if (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    //获取每个列的列名
                    //String columnName = metaData.getColumnName(i+1);
                    //获取列的别名
                    String columnLabel = metaData.getColumnLabel(i+1);
                    //获取每个列的列值
                    Object columnValue = rs.getObject(i + 1);

                    //通过反射，将对象指定名columnName的属性赋值为指定的值columnValue
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);//保证私有属性也可以访问
                    field.set(t, columnValue);//赋值
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);
        }
        return null;
    }

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.print("用户名：");
        String userName = scan.nextLine();
        System.out.print("密   码：");
        String password = scan.nextLine();

        // WHERE USER = ' 1' or ' AND PASSWORD =' =1 or '1' = '1 '
        String sql = "SELECT user,password FROM user_table WHERE user = ? AND password = ?";
        User user = getInstance(User.class, sql, userName, password);
        if (user != null) {
            System.out.println("登陆成功!");
        } else {
            System.out.println("用户名或密码错误！");
        }
    }
}
